import { map, correct, PLAYER, BOX, WALL, SPACE } from './map.js'

const container = document.getElementById('game'),
    piece_size = 45 // 方块尺寸
const title = document.getElementsByClassName('level')[0]

export const player_position = {}    // 玩家位置

export function render_all(level) {
    const cur_map = map[level]
    const cur_correct = correct[level]
    const rows = cur_map.length
    const cols = cur_map[0].length

    title.innerHTML = `第 ${level + 1} 关`
    container.innerHTML = ''
    container.style.width = cols * piece_size + 'px'
    container.style.height = rows * piece_size + 'px'
    for (let row = 0; row < rows; row++) {
        for (let col = 0; col < cols; col++) {
            render_one(row, col)
        }
    }

    // 渲染一个方块
    function render_one(row, col) {
        const value = cur_map[row][col]
        const div = document.createElement('div')
        let cls
        if (value === SPACE) {
            // 空白
            // 是否为正确的格子
            const is_correct = cur_correct.some(item => item.row === row && item.col === col)
            if (!is_correct) {
                return;
            }
            cls = 'correct'
        } else if (value === PLAYER) {
            // 玩家
            cls = 'player'
            // 设置玩家位置
            player_position.row = row
            player_position.col = col
        } else if (value === WALL) {
            // 墙
            cls = 'wall'
        } else if (value === BOX) {
            // 箱子
            const is_correct = cur_correct.some(item => item.row === row && item.col === col)
            if (is_correct) {
                cls = 'box1'
            } else {
                cls = 'box0'
            }
        }
        div.className = cls
        div.style.left = col * piece_size + 'px'
        div.style.top = row * piece_size + 'px'
        container.appendChild(div)
    }
}
